<template>
  <view class="app">
	  
	  <view style="display: flex;width: 100%;">
		  <img src="/static/img/logos.png" alt="Author Avatar"  style="width: 40px;margin-top: 10px;margin-bottom: 10px;"/>
		  <text style="width: 100%;text-align: center;margin-left: -10px;line-height: 50px;font-size: 20px;color:#0081ff;">智学博客</text>
			
		  <!-- <img src="/static/img/tx.jpg" alt="Author Avatar"  style="width: 40px;margin-top: 10px;margin-bottom: 10px;"/> -->
	  </view>
	  
	  		
	  
	  
	  
	 <view class="search-container">
      <view class="search-wrapper">
        <font-awesome-icon :icon="['fas', 'search']" class="search-icon" />
        <input type="text" v-model="searchQuery" placeholder="搜索文章" class="search-input" @keyup.enter="performSearch" />
        <button class="search-button" @click="performSearch">
          <span>
            <font-awesome-icon :icon="['fas', 'search']" /> 搜索
          </span>
        </button>
      </view>
    </view>
    <view class="carousel-container">
		<Carousel />
		
    <!-- <image-carousel :images="carouselData" /> -->
    </view>
    <view class="tag-filter-container">
      <div class="tag-list">
        <span 
          v-for="tag in tags" 
          :key="tag" 
          class="tag" 
          
          @click="selectTag(tag.id)"
        >
          {{ tag.tagName }}
        </span>
      </div>
    </view>
    <view class="main">
      <view class="articles-container">
        <article-item 
          v-for="article in articles" 
          :key="article.id"
          :title="article.title"
          :description="article.content"
          :comments="article.count"
          :views="article.count"
          :initial-likes="article.likesNum"
          :author="article.userPhoto"
          :tags="article.tagName"
          @update:likes="article.likesNum = $event"
		  @click="articlexq(article.id)"
        />
		  <div v-if="loadingMore" class="loading-more">加载中...</div>
		        <div v-if="noMoreData" class="no-more-data">没有更多数据了</div>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted,onUnmounted } from 'vue';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { faSearch, faCheck } from '@fortawesome/free-solid-svg-icons';
import { library } from '@fortawesome/fontawesome-svg-core';
import ArticleItem from './components/ArticleItem.vue';
import ImageCarousel from './components/ImageCarousel.vue';
import { articleList, gettagList, getAdvertisement } from './api/api';
import Carousel from './components/Carousel.vue';
import { useRoute } from 'vue-router';


// 添加图标库
library.add(faSearch, faCheck);

// const articles = ref([]);
// const carouselData = ref([]);
// const tags = ref([]);

// const searchQuery = ref('');
// const selectedTag = ref(null);


const route = useRoute();
const articles = ref([]);
const carouselData = ref([]);
const tags = ref([]);
const tagsId = ref(0);
const currentPage = ref(1);
const loadingMore = ref(false);
const noMoreData = ref(false);

const searchQuery = ref('');
const selectedTag = ref(null);


const handleScroll = () => {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  const windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
  const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

  if (scrollTop + windowHeight >= scrollHeight - 100) {
	  if(route.path  == "/pages/home/home"){
	  
	  loadArticles();
	  }
  }
};


onMounted(async () => {
  try {
	  
	  console.log("22222");
    const [fetchedArticles, fetchedTags] = await Promise.all([
      articleList(0,currentPage.value),
     // getAdvertisement(),
      gettagList()
    ]);
    articles.value = fetchedArticles.data;
   // carouselData.value = fetchedCarouselData.data;
    tags.value = fetchedTags.data;
	//console.log(carouselData );
  } catch (error) {
    console.error('Error fetching data:', error);
  }
  // 添加滚动监听
    window.addEventListener('scroll', handleScroll);
});

const uniqueTags = computed(() => {
  const allTags = articles.value.flatMap(article => article.tags);
  return [...new Set(allTags)];
});


const selectTag = async (tag)=>{
	
	console.log("33333");
	tagsId.value = tag;
	console.log(tagsId.value);
	//await fetchedArticles = articleList(tag);
	const res = await articleList(tagsId.value,currentPage.value);
	articles.value =res.data;
	console.log(res.data);
};

onUnmounted(() => {
  // 移除滚动监听
  window.removeEventListener('scroll', handleScroll);
});



// const selectTag = (tag) => {
//   selectedTag.value = selectedTag.value === tag ? null : tag;
// };

const performSearch = () => {
  // 执行搜索操作
  console.log('执行搜索:', searchQuery.value);
  window.location.href = "/#/pages/search/search?search=" + searchQuery.value;
};

const articlexq = (id) => {
  // 跳转文章详情
  console.log('跳转文章详情:', id);
  window.location.href = "/#/pages/article/detail/detail?id=" + id;//文章详情跳转参数为id
};

// const performSearch = () => {
//   // 执行搜索操作
//   console.log('执行搜索:', searchQuery.value);
//   currentPage.value = 1;
//   loadArticles();
// };

const loadArticles = async () => {
  if (loadingMore.value || noMoreData.value) return;

  loadingMore.value = true;
	
  try {
    //const fetchedArticles = await fetchArticles(currentPage.value + 1);
	console.log("11111");
	const fetchedArticles = await articleList(tagsId.value,currentPage.value + 1);
    if (fetchedArticles.data.length === 0) {
      noMoreData.value = true;
    } else {
      articles.value = [...articles.value, ...fetchedArticles.data];
      currentPage.value++;
    }
  } catch (error) {
    console.error('Error fetching more articles:', error);
  } finally {
    loadingMore.value = false;
  }
};


const filteredArticles = computed(() => {
  return articles.value.filter(article => {
    const query = searchQuery.value.toLowerCase();
    const tagFilter = selectedTag.value ? selectedTag.value.toLowerCase() : '';
    return (
      (article.title.toLowerCase().includes(query) ||
      article.description.toLowerCase().includes(query) ||
      article.tags.some(tag => tag.toLowerCase().includes(query))) &&
      (tagFilter === '' || article.tags.includes(tagFilter))
    );
  });
});
</script>
<style scoped>
.app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  padding: 0 10px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e9f0 100%);
  min-height: 100vh;
  text-align: left; /* 左对齐 */
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e9f0 100%), url('https://via.placeholder.com/1200x800') no-repeat center center fixed;
  background-size: cover;
  display: flex;
  flex-direction: column;
  align-items: center;
  align-items: flex-start;
}

.search-container {
  margin-bottom: 15px;
  width: 100%;
  max-width: 600px;
  text-align: left; /* 左对齐 */
}

.search-wrapper {
  position: relative;
  width: 100%;
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 25px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid #007BFF; /* 搜索框边框颜色 */
  animation: slideIn 1s ease-in-out;
  padding-right: 50px; /* 为按钮留出空间 */
}

.search-icon {
  position: absolute;
  top: 50%;
  left: 10px;
  transform: translateY(-50%);
  color: #999;
  font-size: 14px;
}

.search-input {
  height: 32px;
  border: none;
  border-radius: 25px;
  width: 100%;
  font-size: 14px;
  margin: 0 auto;
  box-sizing: border-box;
  padding-left: 35px; /* 为图标留出空间 */
  text-indent: 10px;
  flex-grow: 1;
  background: transparent;
  outline: none;
  color: #2c3e50; /* 输入框文字颜色 */
  transition: border-color 0.3s ease-in-out;
}

.search-input:focus {
  border-color: #007BFF;
}

.search-button {
  position: absolute;
  top: 50%;
  right: 1px;
  transform: translateY(-50%);
  background: #007BFF;
  color: #fff;
  border: none;
  border-radius: 25px;
  padding: 2px 6px; /* 减小内边距 */
  font-size: 10px; /* 减小字体大小 */
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 3px;
}

.search-button:hover {
  background: #0056b3;
}

.carousel-container {
  width: 100%;
  max-width: 1200px;
  margin-bottom: 15px;
}

.tag-filter-container {
  margin-bottom: 10px; /* 减小上下间隔 */
  overflow-x: auto;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch; /* 使 iOS 设备上的滚动更流畅 */
  width: 100%; /* 固定宽度 */
  max-width: 1200px; /* 最大宽度 */
}

.tag-list {
  display: inline-block;
  padding: 0 5px; /* 为标签列表添加一些内边距 */
}

.tag {
  background: #e4e9f0;
  color: #2c3e50;
  padding: 5px 8px;
  border-radius: 20px;
  font-size: 14px; /* 增大字体大小 */
  cursor: pointer;
  margin-right: 8px;
  display: inline-block;
  transition: background 0.3s ease-in-out, color 0.3s ease-in-out;
}

.tag.active {
  background: #007BFF;
  color: #fff;
}

.tag:hover {
  background: #d8e1ea;
}

.main {
  margin-top: 15px;
  width: 100%;
  max-width: 1200px;
  text-align: left; /* 左对齐 */
}

.articles-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  justify-content: flex-start; /* 左对齐 */
  animation: fadeIn 1s ease-in-out;
}

.article-item {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 10px;
  transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
  border: 1px solid #007BFF; /* 文章列表项边框颜色 */
  background: #f9f9f9; /* 文章列表项背景颜色 */
  width: 100%; /* 宽度为100% */
  box-sizing: border-box; /* 确保内边距和边框不会增加总宽度 */
  animation: fadeInUp 1s ease-in-out;
}

.article-item:hover {
  transform: scale(1.02);
  box-shadow: 0 6px 10px rgba(0, 0, 0, 0.2);
}

.article-item .title {
  font-size: 1.1em;
  color: #007BFF; /* 文章标题颜色 */
  margin-bottom: 8px;
}

.article-item .description {
  color: #555; /* 文章描述颜色 */
  margin-bottom: 8px;
  font-size: 12px;
}

.article-item .metadata {
  color: #999; /* 元数据颜色 */
  font-size: 10px;
  margin-top: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.article-item .metadata .author {
  display: flex;
  align-items: center;
}

.article-item .metadata .author img {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-right: 5px;
}

.article-item .metadata .tags {
  display: flex;
  flex-wrap: wrap;
  gap: 3px;
}
.article-item .metadata .tags span {
  background: #007BFF;
  color: #fff;
  padding: 3px 6px;
  border-radius: 20px;
  font-size: 8px;
}

.loading-more {
  text-align: center;
  margin: 20px 0;
  color: #999;
}

.no-more-data {
  text-align: center;
  margin: 20px 0;
  color: #999;
}

/* 媒体查询 */
@media (max-width: 768px) {
  .articles-container {
    flex-direction: column;
  }

  .article-item {
    width: 100%; /* 移动设备上全宽 */
  }
}

/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    transform: translateX(-20px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes fadeInUp {
  from {
    transform: translateY(20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>